<template>
    <Dialog :title="title" :show="true" @close="cancel" :width="335" :height="515" :left="uiLeft" :top="uiTop">
        <div class="box">
            <div class="texture-content">
                <div class="base-items">
                    <el-checkbox v-model="baseColorFactor.enable" />
                    <span>基础颜色：</span>
                    <div>
                        <el-color-picker v-model="baseColorFactor.value" :disabled="!baseColorFactor.enable" show-alpha
                            class="items-width-small" />
                    </div>
                    <!-- <div>1</div> -->
                </div>
                <!-- <div class="base-items">
                    <el-checkbox v-model="emissiveFactor.enable" />
                    <span>自发光颜色：</span>
                    <el-color-picker v-model="emissiveFactor.value" :disabled="!emissiveFactor.enable" show-alpha
                        class="items-width-small" />
                    </div> -->
                <div class="base-items">
                    <el-checkbox v-model="metallicFactor.enable" />
                    <span>金属度：</span>
                    <el-slider size="small" :max="1" :step="0.001" v-model.lazy="metallicFactor.value"
                        :disabled="!metallicFactor.enable" class="items-width-large" />
                    <!-- <div>1</div> -->
                </div>
                <div class="base-items">
                    <el-checkbox v-model="roughnessFactor.enable" />
                    <span>粗糙度：</span>
                    <el-slider size="small" :max="1" :step="0.001" v-model.lazy="roughnessFactor.value"
                        :disabled="!roughnessFactor.enable" class="items-width-large" />
                    <!-- <div>1</div> -->
                </div>
                <div class="base-items">
                    <el-checkbox v-model="doubleSided.enable" />
                    <span>是否双面：</span>
                    <el-switch v-model="doubleSided.value" :disabled="!doubleSided.enable" />
                </div>
                <div class="base-items">
                    <el-checkbox v-model="ulint.enable" />
                    <span>无光照：</span>
                    <el-switch v-model="ulint.value" :disabled="!ulint.enable" />
                </div>
                <div class="base-items">
                    <el-checkbox v-model="alphaModel.enable" />
                    <span>透明模式：</span>
                    <el-select v-model="alphaModel.value" placeholder="请选择" :disabled="!alphaModel.enable"
                        class="items-width-large">
                        <el-option v-for="(item, index) in selectTransparent" :key="item.value" :label="item.type"
                            :value="item.value" />
                    </el-select>
                </div>

                <!-- 基础纹理 -->
                <div class="base-texture">
                    <el-checkbox v-model="baseColorTexture.enable" />
                    <span>基础纹理：</span>
                    <el-input v-model="baseColorTexture.value" :disabled="!baseColorTexture.enable" />
                    <img v-if="baseColorTexture.enable" src="../../../assets/cimrts/beautifyMaterails/choose.png"
                        @click="currentDialog = 'baseTexture'" alt="" style="cursor: pointer;" />
                    <img v-else src="../../../assets/cimrts/beautifyMaterails/unchoose.png" alt="" />
                    <!-- <div>1</div> -->
                </div>
                <div class="base-list">
                    <p></p>
                    <span>UV偏移：</span>
                    <el-input v-model="baseColorTexture.translate[0]" type="number" :disabled="!baseColorTexture.enable"
                        :step="0.1" :min="-1" :max="1" />
                    <el-input v-model="baseColorTexture.translate[1]" type="number" :disabled="!baseColorTexture.enable"
                        :step="0.1" :min="-1" :max="1" />
                </div>
                <div class="base-list">
                    <p></p>
                    <span>UV缩放：</span>
                    <el-input v-model="baseColorTexture.scale[0]" type="number" :disabled="!baseColorTexture.enable"
                        :step="0.1" />
                    <el-input v-model="baseColorTexture.scale[1]" type="number" :disabled="!baseColorTexture.enable"
                        :step="0.1" />
                </div>
                <div class="base-uv">
                    <p></p>
                    <span>UV旋转：</span>
                    <el-slider size="small" :max="360" :step="1" v-model="baseColorTexture.rotate"
                        :disabled="!baseColorTexture.enable" />
                </div>


                <!-- 法向纹理 -->
                <div class="base-texture">
                    <el-checkbox v-model="normalTexture.enable" />
                    <span>法向纹理：</span>
                    <el-input v-model="normalTexture.value" :disabled="!normalTexture.enable" />
                    <img v-if="normalTexture.enable" src="../../../assets/cimrts/beautifyMaterails/choose.png"
                        @click="currentDialog = 'normalTexture'" alt="" style="cursor: pointer;" />
                    <img v-else src="../../../assets/cimrts/beautifyMaterails//unchoose.png" alt="" />
                    <!-- <div>1</div> -->
                </div>
                <div class="base-list">
                    <p></p>
                    <span>UV偏移：</span>
                    <el-input v-model="normalTexture.translate[0]" type="number" :disabled="!normalTexture.enable"
                        :step="0.1" :min="-1" :max="1" />
                    <el-input v-model="normalTexture.translate[1]" type="number" :disabled="!normalTexture.enable"
                        :step="0.1" :min="-1" :max="1" />
                </div>
                <div class="base-list">
                    <p></p>
                    <span>UV缩放：</span>
                    <el-input v-model="normalTexture.scale[0]" type="number" :disabled="!normalTexture.enable"
                        :step="0.1" />
                    <el-input v-model="normalTexture.scale[1]" type="number" :disabled="!normalTexture.enable"
                        :step="0.1" />
                </div>
                <div class="base-uv">
                    <p></p>
                    <span>UV旋转：</span>
                    <el-slider size="small" :max="360" :step="1" v-model="normalTexture.rotate"
                        :disabled="!normalTexture.enable" />
                </div>
                <div class="base-items">
                    <el-checkbox v-model="magfilter.enable" />
                    <span>放大采样：</span>
                    <el-select v-model="magfilter.value" placeholder="请选择" :disabled="!magfilter.enable"
                        class="items-width-large">
                        <el-option v-for="item in selectmagfilter" :key="item.value" :label="item.type"
                            :value="item.value" />
                    </el-select>
                </div>
                <div class="base-items">
                    <el-checkbox v-model="minfilter.enable" />
                    <span>缩小采样：</span>
                    <el-select v-model="minfilter.value" placeholder="请选择" :disabled="!minfilter.enable"
                        class="items-width-large">
                        <el-option v-for="item in selectminfilter" :key="item.value" :label="item.type"
                            :value="item.value" />
                    </el-select>
                </div>
            </div>
            <div class="texture-bottom">
                <div class="bottom-left">
                    <el-button @click.stop="cancelClaer">取消</el-button>
                </div>
                <div class="bottom-right">
                    <el-button @click.stop="cancelClaer">取消</el-button>
                    <el-button @click.stop="confirm">确定</el-button>
                </div>
            </div>
        </div>
    </Dialog>
    <TexturePanel v-if="currentDialog == 'baseTexture'" :title="'选择纹理'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="baseTextureConfirm" :datasetName="datasetName" />
    <TexturePanel v-if="currentDialog == 'normalTexture'" :title="'选择纹理'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="normalTextureConfirm" :datasetName="datasetName" />
</template>
<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import { cellStyle2, cellStyleSmall } from "@/scripts/tableStyle";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import {
    createVueDisposer,
    toVR
} from "earthsdk-ui";
import TexturePanel from "./TexturePanel.vue";
import { WaterMend } from "@/scripts/cimrtsManager/waterMend";
import { debounce } from "lodash";
import { convertRGBA, XEToRGBA } from "@/scripts/utils";
import { ElMessage } from "element-plus";

const props = withDefaults(defineProps<{ title: string, sceneObject: any, createOrEdit: string }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    closeClaer()
    emits("cancel");
};

const uiLeft = document.body.clientWidth - 70 - 335;
// const uiLeft = 10;

const uiTop = document.body.clientHeight - document.body.clientHeight / 2;

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();

const cimrtsManager = getProjectManager().cimrtsManager;

const waterMend = cimrtsManager.waterMend as WaterMend

// cimrts服务ip
const cimrtsIpRef = toVR(d, [cimrtsManager, "cimrtsIp"]);

const currentDialog = ref<any>(undefined)

/**
 * 基础纹理选择
 * @param val 
 */
const baseTextureConfirm = (val: any) => {
    currentDialog.value = undefined
    // baseColorTexture.value.value = `${cimrtsIpRef.value}/ds/featuretiles/${datasetName.value}/${val}`
    baseColorTexture.value.value = `${val}`
}

/**
 * 法向纹理选择
 * @param val 
 */
const normalTextureConfirm = (val: any) => {
    currentDialog.value = undefined
    // normalTexture.value.value = `${cimrtsIpRef.value}/ds/featuretiles/${datasetName.value}/${val}`
    normalTexture.value.value = `${val}`

}

// 基础颜色
const baseColorFactor = ref({
    enable: false,
    value: 'rgba(255,255,255,1)'
})
// 自发光
const emissiveFactor = ref({
    enable: false,
    value: 'rgba(255,255,255,1)'
})
// 金属度
const metallicFactor = ref({
    "enable": false,
    "value": 0
})

// 粗糙度
const roughnessFactor = ref({
    "enable": false,
    "value": 1
})
// 是否双面
const doubleSided = ref({
    "enable": false,
    "value": false
})

// 无光照
const ulint = ref({
    "enable": false,
    "value": false
})
const selectTransparent = ref([
    {
        type: '不透明',
        value: ' '
    },
    {
        type: '混合模式',
        value: 'BLEND'
    },
    {
        type: '遮罩模式',
        value: 'MASK'
    },

])
// 透明模式
const alphaModel = ref({
    "enable": false,
    "value": ""
})
// 基础纹理
const baseColorTexture = ref({
    "enable": false,
    "value": "",
    "translate": [
        0,
        0
    ],
    "scale": [
        1,
        1
    ],
    "rotate": 0
})

// 法向纹理
const normalTexture = ref({
    "enable": false,
    "value": "",
    "translate": [
        0,
        0
    ],
    "scale": [
        1,
        1
    ],
    "rotate": 0
})

// 放大采样
const magfilter = ref({
    "enable": false,
    "value": null
})
const selectmagfilter = ref(
    [
        {
            type: 'NEAREST',
            value: 9728
        },
        {
            type: 'LINEAR',
            value: 9729
        },


    ]
)
// 缩小采样
const minfilter = ref({
    "enable": false,
    "value": null
})


const selectminfilter = ref(
    [
        {
            type: 'NEAREST',
            value: 9728
        },
        {
            type: 'LINEAR',
            value: 9729
        },
        {
            type: 'NEAREST_MIPMAP_NEAREST',
            value: 9984
        },
        {
            type: 'LINEAR_MIPMAP_NEAREST',
            value: 9985
        },
        {
            type: 'NEAREST_MIPMAP_LINEAR',
            value: 9986
        },
        {
            type: 'LINEAR_MIPMAP_LINEAR',
            value: 9987
        }

    ]
)



const datasetName = ref("");

const init = () => {
    datasetName.value = props.sceneObject.datasetName;
    if (Object.entries(props.sceneObject.beautifyMaterails).length) {
        baseColorFactor.value = {
            enable: props.sceneObject.beautifyMaterails.baseColorFactor.enable,
            value: XEToRGBA(props.sceneObject.beautifyMaterails.baseColorFactor.value)
        }
        metallicFactor.value = props.sceneObject.beautifyMaterails.metallicFactor
        roughnessFactor.value = props.sceneObject.beautifyMaterails.roughnessFactor
        doubleSided.value = props.sceneObject.beautifyMaterails.doubleSided
        ulint.value = props.sceneObject.beautifyMaterails.ulint
        alphaModel.value = props.sceneObject.beautifyMaterails.alphaModel
        baseColorTexture.value = props.sceneObject.beautifyMaterails.baseColorTexture
        normalTexture.value = props.sceneObject.beautifyMaterails.normalTexture
        magfilter.value = props.sceneObject.beautifyMaterails.magfilter
    }
}

watch([magfilter, minfilter, baseColorFactor, emissiveFactor, metallicFactor, roughnessFactor, doubleSided, ulint, alphaModel, baseColorTexture, normalTexture], async () => {
    if (!baseColorFactor.value.value) {
        baseColorFactor.value.value = 'rgba(255,255,255,1)'
    }
    const data: any = {
        baseColorFactor: {
            enable: baseColorFactor.value.enable,
            value: convertRGBA(baseColorFactor.value.value)
        },
        // emissiveFactor: {
        //     enable: emissiveFactor.value.enable,
        //     value: convertRGBA(emissiveFactor.value.value)
        // },
        metallicFactor: { ...metallicFactor.value },
        roughnessFactor: { ...roughnessFactor.value },
        doubleSided: { ...doubleSided.value },
        ulint: { ...ulint.value },
        alphaModel: { ...alphaModel.value },
        baseColorTexture: {
            "enable": baseColorTexture.value.enable,
            "value": baseColorTexture.value.value,
            "translate": [
                +baseColorTexture.value.translate[0],
                +baseColorTexture.value.translate[1]
            ],
            "scale": [

                +baseColorTexture.value.scale[0],
                +baseColorTexture.value.scale[1]
            ],
            "rotate": baseColorTexture.value.rotate
        },
        normalTexture: {
            "enable": normalTexture.value.enable,
            "value": normalTexture.value.value,
            "translate": [
                +normalTexture.value.translate[0],
                +normalTexture.value.translate[1]
            ],
            "scale": [
                +normalTexture.value.scale[0],
                +normalTexture.value.scale[1]
            ],
            "rotate": normalTexture.value.rotate
        },
        magfilter: { ...magfilter.value },
        minfilter: { ...minfilter.value }
    }
    // props.sceneObject.beautifyMaterails = { ...data }

    await props.sceneObject.setMaterial("default")
    const material: any = {}
    data.baseColorFactor.enable && (material.baseColorFactor = [...data.baseColorFactor.value])
    data.metallicFactor.enable && (material.metallicFactor = data.metallicFactor.value)
    data.roughnessFactor.enable && (material.roughnessFactor = data.roughnessFactor.value)
    data.doubleSided.enable && (material.doubleSided = data.doubleSided.value)
    data.ulint.enable && (material.unlit = data.ulint.value)
    data.alphaModel.enable && (material.alphaMode = data.alphaModel.value)
    data.magfilter.enable && (material.magfilter = selectmagfilter.value.find((item) => item.value == data.magfilter.value)?.type)
    data.minfilter.enable && (material.minfilter = selectminfilter.value.find((item) => item.value == data.minfilter.value)?.type)

    if (data.baseColorTexture.enable && data.baseColorTexture.value) {
        material.baseColorTexture = {
            value: `${cimrtsIpRef.value}/ds/featuretiles/${datasetName.value}/${data.baseColorTexture.value}`,
            offset: data.baseColorTexture.translate,
            scale: data.baseColorTexture.scale,
            rotate: data.baseColorTexture.rotate,
        }
    }
    if (data.normalTexture.enable && data.normalTexture.value) {
        material.normalTexture = {
            value: `${cimrtsIpRef.value}/ds/featuretiles/${datasetName.value}/${data.normalTexture.value}`,
            offset: data.normalTexture.translate,
            scale: data.normalTexture.scale,
            rotate: data.normalTexture.rotate,
        }
    }
    console.log("material", material);

    const res = await props.sceneObject.setMaterial(material)
    if (res.type == "warn") {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }

}, { deep: true })

const claer = async () => {

    await props.sceneObject.setMaterial("default")
    // 基础颜色
    baseColorFactor.value = {
        enable: false,
        value: 'rgba(255,255,255,1)'
    }

    // 金属度
    metallicFactor.value = {
        "enable": false,
        "value": 0
    }

    // 粗糙度
    roughnessFactor.value = {
        "enable": false,
        "value": 1
    }
    // 是否双面
    doubleSided.value = {
        "enable": false,
        "value": false
    }

    // 无光照
    ulint.value = {
        "enable": false,
        "value": false
    }

    // 透明模式
    alphaModel.value = {
        "enable": false,
        "value": ""
    }
    // 基础纹理
    baseColorTexture.value = {
        "enable": false,
        "value": "",
        "translate": [
            0,
            0
        ],
        "scale": [
            1,
            1
        ],
        "rotate": 0
    }

    // 法向纹理
    normalTexture.value = {
        "enable": false,
        "value": "",
        "translate": [
            0,
            0
        ],
        "scale": [
            1,
            1
        ],
        "rotate": 0
    }

    // 放大采样
    magfilter.value = {
        "enable": false,
        "value": null
    }
    // 缩小采样
    minfilter.value = {
        "enable": false,
        "value": null
    }

}

const closeClaer = async () => {
    if (Object.entries(props.sceneObject.beautifyMaterails).length) return;
    await claer()

}

const cancelClaer = async () => {
    await claer()
    props.sceneObject.beautifyMaterails = {}

}

const confirm = () => {
    const data: any = {
        baseColorFactor: {
            enable: baseColorFactor.value.enable,
            value: convertRGBA(baseColorFactor.value.value)
        },
        // emissiveFactor: {
        //     enable: emissiveFactor.value.enable,
        //     value: convertRGBA(emissiveFactor.value.value)
        // },
        metallicFactor: { ...metallicFactor.value },
        roughnessFactor: { ...roughnessFactor.value },
        doubleSided: { ...doubleSided.value },
        ulint: { ...ulint.value },
        alphaModel: { ...alphaModel.value },
        baseColorTexture: {
            "enable": baseColorTexture.value.enable,
            "value": baseColorTexture.value.value,
            "translate": [
                +baseColorTexture.value.translate[0],
                +baseColorTexture.value.translate[1]
            ],
            "scale": [

                +baseColorTexture.value.scale[0],
                +baseColorTexture.value.scale[1]
            ],
            "rotate": baseColorTexture.value.rotate
        },
        normalTexture: {
            "enable": normalTexture.value.enable,
            "value": normalTexture.value.value,
            "translate": [
                +normalTexture.value.translate[0],
                +normalTexture.value.translate[1]
            ],
            "scale": [
                +normalTexture.value.scale[0],
                +normalTexture.value.scale[1]
            ],
            "rotate": normalTexture.value.rotate
        },
        magfilter: { ...magfilter.value },
        minfilter: { ...minfilter.value }
    }
    props.sceneObject.beautifyMaterails = { ...data }
    ElMessage.success("材质保暂存成功")
}

watch(() => props.sceneObject, async () => {
    console.log("props.sceneObject", props.sceneObject);

    await closeClaer()
    init()
}, { immediate: true })

onMounted(() => {
});
onBeforeUnmount(() => {
});
</script>

<style scoped>
.box {
    padding: 10px 15px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
}

.base-uv {
    display: grid;
    grid-template-columns: 15px 90px 150px;
    align-items: center;
    padding-bottom: 10px;

    grid-column-gap: 10px;


}

.base-texture {
    display: grid;
    grid-template-columns: 15px 90px 120px 20px;
    align-items: center;
    padding-bottom: 10px;
    grid-column-gap: 10px;

}

.base-list {
    display: grid;
    grid-template-columns: 15px 90px 70px 70px;
    align-items: center;
    padding-bottom: 10px;
    grid-column-gap: 10px;
}

.base-items {
    display: grid;
    grid-template-columns: 15px 90px 150px;
    align-items: center;
    padding-bottom: 10px;
    grid-column-gap: 10px;

}

:deep(.el-select) {
    width: 150px;
}

:deep(.el-select__wrapper) {
    width: 150px;
}

.texture-content {
    height: calc(100% - 45px);
    overflow-y: auto;
}

.texture-bottom {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    height: 35px;

}
</style>
